﻿
@using Gx.Model.Entity;
@using Gx.Model.Enums;
@model LKWarehouseContract
@{
    ViewBag.Title = "新建包仓合同";
    Layout = "~/Views/Shared/InfoMaste.cshtml";
}

<link href="~/Content/css/custome.css" rel="stylesheet" />
<div title="新建包仓合同" style="width:auto; height:auto; padding-left:5px; font-size:14px;  ">
    <div class="ftitle">
        <a href="javascript:" class="easyui-linkbutton" iconCls="icon-ok" style="height:32px" onclick="saveData()">保存</a>
        <a href="/LKWarehouseContract/LKWarehouseContractList" class="easyui-linkbutton" iconCls="icon-back" style="height:32px">返回</a>
    </div>
    <form id="fm" method="post" novalidate>
        <div class="ftitle">基础信息</div>
        <div class="fitem1">
            <label>
                单据编号:
            </label>
            <input class="easyui-textbox" readonly="readonly" value="系统自动生成" style="width: 173px; height: 30px;">
            <label>
                客户:
            </label>
            <select class="easyui-combogrid" style="width: 173px; height: 30px;" name="CustomerId" id="CustomerId" data-options="required:true"></select>
            <label>
                客户名称:
            </label>
            <input name="CustomerName" id="CustomerName" class="easyui-textbox" style="width: 173px; height: 30px;" readonly="readonly" data-options="required:true" />
        </div>
        <div class="fitem1">
            <label>
                开单日期:
            </label>
            <input class="easyui-datebox" name="ContractTime" id="ContractTime" value="@Model.ContractTime" style="width: 173px; height: 30px; " data-options="required:true">
            <label>
                开始日期:
            </label>
            <input class="easyui-datebox" name="BeginTime" id="BeginTime" style="width: 173px; height: 30px; " data-options="required:true,onChange:calculateAmount">
            <label>
                结束日期:
            </label>
            <input class="easyui-datebox" name="EndTime" id="EndTime" style="width: 173px; height: 30px; " data-options="required:true,onChange:calculateAmount">
        </div>
        <div class="fitem1">
            <label>
                包仓类型:
            </label>
            <select class="easyui-combobox" style="width: 173px; height: 30px;" name="StoreType" id="StoreType"></select>
            <label>
                包仓算法:
            </label>
            <select class="easyui-combobox" style="width: 173px; height: 30px;" name="StoreAlgorithm" id="StoreAlgorithm" data-options="required:true,onChange:calculateAmount"></select>
            <label>
                单价（月）:
            </label>
            <input name="UnitPrice" id="UnitPrice" class="easyui-numberbox" value="@Model.UnitPrice" data-options="required: true,precision:'2',onChange:calculateAmount" style="width: 173px; height: 30px;" autocomplete="off" />
        </div>
        <div class="fitem1">
            <label>
                数量:
            </label>
            <input name="Number" id="Number" value="@Model.Number" class="easyui-numberbox" data-options="required: true,onChange:calculateAmount" style="width: 173px; height: 30px;" autocomplete="off" />
            <label>
                总金额:
            </label>
            <input name="Amount" id="Amount" value="@Model.Amount" class="easyui-numberbox" data-options="required: true,precision:'2'" style="width: 173px; height: 30px;" autocomplete="off" />
            <label>
                按吨操作:
            </label>
            <input class="easyui-switchbutton" id="sbIsByTon" data-options="onText:'是',offText:'否'">
        </div>
        <div class="fitem1">
            <label>
                仓库:
            </label>
            <select class="easyui-combobox" value="@Model.WareHouseId" style="width: 173px; height: 30px;" name="WareHouseId" id="WareHouseId"></select>
        </div>
        <div class="fitem1">
            <label>
                图片:
            </label>
            <input type="hidden" id="hidFileId" />
            <input id="filebox" class="easyui-filebox" name="file" data-options="buttonText:'选择文件',accept:'image/*',onChange:fileChange" />
        </div>
        <div class="fitem1">
            <label>
                备注:
            </label>
            <textarea rows="4" cols="4" style="width: 400px; height: 90px; vertical-align: top" name="Remark" id="Remark" autocomplete="off" placeholder="200字以内"></textarea>
        </div>

        <div id="Wl">
            <div id="tabs" class="easyui-tabs" fit="true" border="false" style="width: 500px; height: 300px; ">
                <div title="包仓明细">

                    <table class="gridtable" id="detailgird">
                        <thead>
                            <tr>
                                <th>开始日期</th>
                                <th>结束日期</th>
                                <th>单价</th>
                                <th>数量</th>
                                <th>原金额</th>
                                <th>总金额</th>
                                <th>已结算</th>
                                <th>是否收费</th>
                            </tr>
                        </thead>
                    </table>
                </div>
                <div title="默认杂费设置">
                    <a href="javascript:" class="easyui-linkbutton" iconcls="icon-add" plain="true" onclick="addDom()">添加</a>
                    <table class="gridtable" id="costgird">
                        <thead>
                            <tr>
                                <th>费用类别</th>
                                <th>价格</th>
                                <th>单位</th>
                                <th>在入库单显示</th>
                                <th>在出库单显示</th>
                                <th>在调仓单显示</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
        @Html.Partial("~/Views/Shared/_CreateUserAndModifyUser.cshtml")
    </form>
    <div id="customerselecttoolbar2">
        <input id="SelectCustomerText2" class="easyui-textbox " style="width: 173px; height: 30px;" />
        <a href="javascript:" class="easyui-linkbutton" plain="true" iconcls="icon-search" onclick="querycustomer2()">查询</a>
    </div>
</div>
<script src="~/Js/Global.js?v=20240706"></script>
<script type="text/javascript">

    $(function () {
        InitStoreTypeCombobox();
        InitStoreAlgorithmCombobox();
        InitCustomer();
        InitWareHouse();

        $('#sbIsByTon').switchbutton({ checked: @Html.Raw(Model.IsByTon ? "true" : "false") });

        $('#StoreType').combobox('setValue', @Model.StoreType);
        $('#StoreAlgorithm').combobox('setValue', @Model.StoreAlgorithm);
        //$('#EndTime').datebox('setValue', '@Model.EndTime.ToString("yyyy-MM-dd")');
    });


    var costdom = new Array();
    var detaildom = new Array();

    function initDom() {
        //costdom.length = 0;
        detaildom.length = 0;
        //$("input[type='hidden'][id^='CostDomId']").each(function () {
        //    var d = $(this).val();
        //    if ($.inArray(d, costdom) === -1) {
        //        costdom.push(d);
        //    }
        //});
        $("input[type='hidden'][id^='DetailDomId']").each(function () {
            var d = $(this).val();
            if ($.inArray(d, detaildom) === -1) {
                detaildom.push(d);
            }
        });

    }

    var domId = 1;
    function addDom() {
        $.post("/LKWarehouseContract/_AddLKWarehouseContract", { domId: domId }, function (html) {
            $.messager.progress('close');
            $("#costgird").append(html);
            $.parser.parse($("#" + domId));
            InitCostTypesCombogrid(domId);
            domId = Number(domId) + 1;
        });
    }

 
    function delDom(domId) {
        $("#" + domId).remove();
    }

    function querycustomer2() {
        $("#CustomerId").combogrid("grid").datagrid("reload", { "Customer": $("#SelectCustomerText2").val() });
    }

    function saveData() {
        var validate = $("#fm").form("validate")
        if (!validate) {
            return;
        }
        var data = {
            "CustomerId": $("#CustomerId").combobox('getValue'),
            "CustomerName": $("#CustomerName").textbox('getValue'),
            "ContractTime": $("#ContractTime").datebox('getValue'),
            "BeginTime": $("#BeginTime").datebox('getValue'),
            "EndTime": $("#EndTime").datebox('getValue'),
            "StoreType": $("#StoreType").combobox('getValue'),
            "StoreAlgorithm": $("#StoreAlgorithm").combobox('getValue'),
            "UnitPrice": $("#UnitPrice").numberbox('getValue'),
            "Number": $("#Number").numberbox('getValue'),
            "Amount": $("#Amount").numberbox('getValue'),
            "IsByTon": $('#sbIsByTon').switchbutton('options').checked,
            "WareHouseId": $("#WareHouseId").combobox('getValue'),
            "Remark": $("#Remark").val()
        };
        initDom();

        var costList = new Array();
        for (var i = 1; i < domId; i++) {
            var obj = $("#CostType" + i);
            if (obj.length == 0) {
                continue;
            }
            var costTypeId = obj.combogrid('getValue');
            if ($.trim(costTypeId) == "") {
                continue;
            }
            var CostTypeId = $("#CostType" + i).combobox('getValue');
            var CostType = $("#CostType" + i).combobox('getText');
            var Price = $("#Price" + i).numberbox('getValue');
            var Unit = $("#Unit" + i).textbox('getValue');
            var InStorage = $("#sbInStorage" + i).switchbutton('options').checked;
            var OutStorage = $("#sbOutStorage" + i).switchbutton('options').checked;
            var TransferStorage = $("#sbTransferStorage" + i).switchbutton('options').checked;


            if (CostType == "" || Price == "" || Unit == "") {
                Helper.Show("请检查第" + i + "行费用信息");
                return;
            }
            var cost = {
                "CostTypeId": CostTypeId,
                "CostType": CostType,
                "Price": Price,
                "Unit": Unit,
                "InStorage": InStorage,
                "OutStorage": OutStorage,
                "TransferStorage": TransferStorage
            };
            costList.push(cost);
        };

        var detailList = new Array();
        detaildom.forEach(function (value, index) {
            var i = value;
            var BeginTime = $("#BeginTime" + i).datebox('getValue');
            var EndTime = $("#EndTime" + i).datebox('getValue');
            var UnitPrice = $("#UnitPrice" + i).numberbox('getValue');
            var number = $("#Number" + i).numberbox('getValue');
            var TotalPrice = $("#TotalPrice" + i).numberbox('getValue');
            var OriginalAmount = $("#OriginalAmount" + i).numberbox('getValue');
            var IsBalance = $("#sbIsBalance" + i).switchbutton('options').checked;
            var IsCharge = $("#sbIsCharge" + i).switchbutton('options').checked;

            var detail = {
                "BeginTime": BeginTime,
                "EndTime": EndTime,
                "UnitPrice": UnitPrice,
                "Number": number,
                "TotalPrice": TotalPrice,
                "OriginalAmount": OriginalAmount,
                "IsBalance": IsBalance,
                "IsCharge": IsCharge
            };
            detailList.push(detail);
        });

        var d = JSON.stringify({ Bill: data, CostList: costList, DetailList: detailList, AttachmentId: $("#hidFileId").val() });
        $.messager.progress({
            title: '请稍后',
            msg: '数据保存中...',
        });
        window.setTimeout(function () {
            $.ajax({
                url: '/LKWarehouseContract/AddLKWarehouseContract',
                type: "post",
                data: d,
                contentType: 'application/json; charset=utf-8',
                success: function (json) {
                    $.messager.progress('close');
                    Helper.Show(json.Msg);
                    if (json.Success) {
                        setTimeout(function () { window.location.href = "/LKWarehouseContract/LKWarehouseContractList"; }, 2000);
                    }
                }
            });
        }, 2000);
    }

    //function checkDecimal(newValue, oldValue) {
    //    if (newValue.toString().split('.').length > 1) {
    //        var decimalPart = newValue.toString().split('.')[1];
    //        if (decimalPart.length > 2) {
    //            //$.messager.alert('Warning', '超过两位小数！');
    //            $(this).numberbox('setValue', oldValue);
    //        }
    //    }
    //}
    //function setFixRate() {
    //    //	var value = $('._fixRate').numberbox('getValue');//不能使用numberbox的getValue,这个是隐藏框的值
    //    //如果有小数点
    //    var value = $('#Balance').val();//这个才是输入框的值
    //    if (value.indexOf(".") >= 0) {//如果包含小数点
    //        if ((value.substring(value.indexOf(".") + 1).length) >= 2) {//如果小数位数已经有两位
    //            $('#Balance').numberbox('options').filter = function () {
    //                //让filter返回false会禁止按键输入
    //                return false;
    //            };
    //        } else {
    //            //记得写else,否则该nunberbox将不允许再次输入了
    //            $('#Balance').numberbox('options').filter = function () {
    //                return true;
    //            }
    //        }
    //    }
    //}


    var detaildomId = 1;
    //计算总金额
    function calculateAmount() {
        //按自然月计算，一个月按30天计算，1，用单价（月）除以30天得到单价，2,计算天数，用结束时间减去开始时间，3,用单价乘以数量乘以天数得到总金额
        //按自然天计算，1,用单价乘以数量乘以天数得到总金额

        var unitPrice = $("#UnitPrice").numberbox('getValue');
        var number = $("#Number").numberbox('getValue');
        var beginTime = $("#BeginTime").datebox('getValue');
        var endTime = $("#EndTime").datebox('getValue');

        //获取包仓算法  1:自然月 2:计费月 3:自然天
        var storeAlgorithm = $("#StoreAlgorithm").combobox('getValue');

        var months = [];
        if (storeAlgorithm == 2) {
            months = dateCutByMonth2(beginTime, endTime);
        } else {
            months = dateCutByMonth(beginTime, endTime);
        }
         

        var days = 0;
        months.forEach(function (value, index) {
            var day = (new Date(value.endDate).getTime() - new Date(value.beginDate).getTime()) / (1000 * 60 * 60 * 24);
            day = day + 1;
            if (day > 30)
            {
                day = 30;
            }
            days += day;
        })

        //var days = (new Date(endTime).getTime() - new Date(beginTime).getTime()) / (1000 * 60 * 60 * 24);

        
        if (storeAlgorithm != 3) {

            unitPrice = unitPrice / 30;
        }
        var amount = unitPrice * number * days;//(days + 1);
        $("#Amount").numberbox('setValue', amount.toFixed(2));

        if (amount > 0) {
            //detaildomId，移除detaildom，重新添加
            //if (detaildomId > 1) {
            //    for (var i = 1; i < detaildomId; i++) {
            //        $("#detail" + i).remove();
            //    }
            //}
            $("tr[id*='detail']").remove();

            var details = [];
            months.forEach(function (value, index) {
                var detailUnitPrice = $("#UnitPrice").numberbox('getValue');
                var day = (new Date(value.endDate).getTime() - new Date(value.beginDate).getTime()) / (1000 * 60 * 60 * 24);
                day = day + 1;
                if (day > 30) {
                    day = 30;
                }
                if (storeAlgorithm != 3) {

                    detailUnitPrice = detailUnitPrice / 30;
                }
                var detailamount = detailUnitPrice * number * day;
                var detail = {
                    "BeginTime": value.beginDate,
                    "EndTime": value.endDate,
                    "UnitPrice": $("#UnitPrice").numberbox('getValue'),
                    "Number": number,
                    "TotalPrice": detailamount.toFixed(2)
                };
                details.push(detail);
            });
            //var detail = {
            //    "BeginTime": beginTime,
            //    "EndTime": endTime,
            //    "UnitPrice": unitPrice,
            //    "Number": number,
            //    "TotalPrice": amount.toFixed(2)
            //};
            $.post("/LKWarehouseContract/_AddLKWarehouseContractDetail", { DetailDomId: detaildomId, DetailList: details }, function (html) {
                $.messager.progress('close');
                $("#detailgird").append(html);

                //$.parser.parse($("#detail" + detaildomId));
                detaildomId = Number(detaildomId) + 1;
            });

        }
    }

    //计算金额
    function calculateAmount2() {
        initDom();

        var totalAmount = 0.00;
        detaildom.forEach(function (value, index) {
            var i = value;
            var totalprice = $("#TotalPrice" + i).numberbox('getValue') * 1;
            totalAmount += totalprice;
        });
        $("#Amount").numberbox('setValue', totalAmount);
    }
</script>





